import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Card, Button, DatePicker, Alert, Tooltip } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import queryString from 'query-string';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Supplier from '../../components/NsSupplier';
import DictCode from '../../components/DictCode';
import TextOverFlow from '../../components/TextOverFlow';
import styles from '@/utils/utils.less';

const FormItem = Form.Item;
const { MonthPicker } = DatePicker;

@connect(({ incexpcompns, loading }) => ({
  pageData: incexpcompns.pageData,
  loading: loading.models.incexpcompns,
  tabList: incexpcompns.tabList,
  expandForm: incexpcompns.expandForm,
  activeKey: incexpcompns.activeKey,
  formFieldsValue: incexpcompns.formFieldsValue,
  valuesArr: incexpcompns.valuesArr,
}))
@Form.create()
class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedRows: [],
      selectedRowKeys: [],
    };

    this.tableSearchLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 15 } },
    };
  }

  componentDidMount() {
    this.getInitialList();
  }

  getInitialList = () => {
    const {
      pageData: { pagination },
      dispatch,
      location,
      formFieldsValue,
      activeKey,
    } = this.props;
    const tempActiveKey = queryString.parse(location.search).activeKey || activeKey;
    if (location.queryParam) {
      dispatch({
        type: 'incexpcompns/updateModalData',
        payload: { formFieldsValue: location.queryParam, expandForm: true },
      });
    }
    dispatch({
      type: 'incexpcompns/updateModalData',
      payload: {
        activeKey: tempActiveKey,
      },
    });
    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      tempActiveKey,
      pagination.current,
      pagination.pageSize
    );
  };

  // 点击查询按钮
  searchBtnList = activeKey => {
    const { form, valuesArr, dispatch } = this.props;
    form.validateFieldsAndScroll([...valuesArr], (err, values) => {
      if (!err) {
        dispatch({
          type: 'incexpcompns/updateModalData',
          payload: {
            formFieldsValue: values,
            activeKey,
          },
        });
        this.searchList(this.processFormData(values), activeKey);
      }
    });
  };

  // 查询
  searchList = (
    formFieldsValue,
    activeKey = '1',
    currentPage = 1,
    pageSize = 10,
    isClear = true
  ) => {
    if (isClear) {
      this.setState({ selectedRows: [], selectedRowKeys: [] });
    }

    const { dispatch } = this.props;
    const pageArg = { currentPage, pageSize };
    const values = {
      ...formFieldsValue,
      pageArg,
    };

    dispatch({
      type: 'incexpcompns/updateModalData',
      payload: {
        values,
        activeKey,
      },
    });

    dispatch({
      type: 'incexpcompns/fetchList',
      payload: {
        ...values,
      },
    });
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'billYm') {
        tempFieldsValue[key] =
          (tempFieldsValue[key] && tempFieldsValue[key].format('YYYYMM')) || null;
      }
      formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
    });
    return formFieldsValue;
  };

  // 切换表格展开收起
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'incexpcompns/updateModalData',
      payload: {
        expandForm: !expandForm,
      },
    });
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { activeKey, formFieldsValue } = this.props;
    this.searchList(
      this.processFormData(formFieldsValue),
      activeKey,
      pagination.current,
      pagination.pageSize,
      false
    );
  };

  // 重置
  resetSearch = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'incexpcompns/updateModalData',
      payload: { formFieldsValue: {} },
    });
    form.resetFields();
    form.setFieldsValue({ billYm: null });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      activeKey,
      formFieldsValue,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="签约方">
              {getFieldDecorator('sendSuppId', {
                initialValue: formFieldsValue.sendSuppId,
              })(<Supplier allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="账单年月">
              {getFieldDecorator('billYm')(
                <MonthPicker placeholder="请选择" style={{ width: '100%' }} format="YYYY-MM" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button
                type="primary"
                htmlType="submit"
                onClick={() => this.searchBtnList(activeKey)}
              >
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      activeKey,
      formFieldsValue,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="签约方">
              {getFieldDecorator('sendSuppId', {
                initialValue: formFieldsValue.sendSuppId,
              })(<Supplier allowClear params={{ status: 2 }} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="账单年月">
              {getFieldDecorator('billYm')(
                <MonthPicker placeholder="请选择" style={{ width: '100%' }} format="YYYY-MM" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.tableSearchLayout} label="实支状态">
              {getFieldDecorator('budgState', {
                initialValue: formFieldsValue.budgState,
              })(<DictCode dictType="BUDGET_STATE" allowClear />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24} />
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <div style={{ float: 'right', marginBottom: 24 }}>
                <Button
                  type="primary"
                  htmlType="submit"
                  onClick={() => this.searchBtnList(activeKey)}
                >
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起
                  <UpOutlined />
                </a>
              </div>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const { pageData, loading, activeKey } = this.props;
    const { selectedRows, selectedRowKeys } = this.state;
    const columns = [
      {
        title: '签约方',
        dataIndex: 'sendSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '账单年月',
        dataIndex: 'billYmStr',
        sorter: (a, b) => new Date(b.billYm) - new Date(a.billYm),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val && moment(val).format('YYYY-MM')) || '--',
      },
      {
        title: '实支状态',
        dataIndex: 'budgStateName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <Tooltip
            placement="top"
            title={
              <div>
                <p>
                  养老：
                  {record.pensBudgStateName || '--'}
                </p>
                <p>
                  失业：
                  {record.unempBudgStateName || '--'}
                </p>
                <p>
                  工伤：
                  {record.injBudgStateName || '--'}
                </p>
                <p>
                  医疗：
                  {record.medBudgStateName || '--'}
                </p>
                <p>
                  生育：
                  {record.birthBudgStateName || '--'}
                </p>
                <p>
                  社保其他费用：
                  {record.insOthBudgStateName || '--'}
                </p>
                <p>
                  公积金：
                  {record.accuBudgStateName || '--'}
                </p>
              </div>
            }
          >
            <span>{(text && `${text}...`) || '--'}</span>
          </Tooltip>
        ),
      },
      {
        title: '差异金额',
        dataIndex: 'diffAmo',
        align: 'right',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        onCell: () => ({ style: { textAlign: 'right' } }),
        render: (text, record) => (
          <Tooltip
            placement="top"
            title={
              <div>
                <p>
                  养老：
                  {record.pensDiffAmo || record.pensDiffAmo === 0
                    ? record.pensDiffAmo.toFixed(2)
                    : '--'}
                </p>
                <p>
                  失业：
                  {record.unempDiffAmo || record.unempDiffAmo === 0
                    ? record.unempDiffAmo.toFixed(2)
                    : '--'}
                </p>
                <p>
                  工伤：
                  {record.injDiffAmo || record.injDiffAmo === 0
                    ? record.injDiffAmo.toFixed(2)
                    : '--'}
                </p>
                <p>
                  医疗：
                  {record.medDiffAmo || record.medDiffAmo === 0
                    ? record.medDiffAmo.toFixed(2)
                    : '--'}
                </p>
                <p>
                  生育：
                  {record.birthDiffAmo || record.birthDiffAmo === 0
                    ? record.birthDiffAmo.toFixed(2)
                    : '--'}
                </p>
                <p>
                  社保其他费用：
                  {record.insOthDiffAmo || record.insOthDiffAmo === 0 ? record.insOthDiffAmo : '--'}
                </p>
                <p>
                  公积金：
                  {record.accuDiffAmo || record.accuDiffAmo === 0
                    ? record.accuDiffAmo.toFixed(2)
                    : '--'}
                </p>
              </div>
            }
          >
            <span>{text === 0 ? 0 : (text && text) || '--'}</span>
          </Tooltip>
        ),
      },
      {
        title: '差异人数',
        dataIndex: 'diffNum',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        align: 'center',
        render: val => <span>{val === 0 ? 0 : (val && val) || '--'}</span>,
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        align: 'center',
        render: (text, record) => (
          <a
            onClick={() =>
              router.push(
                `/searchmanage/incexpcompns/detail?activeKey=${activeKey}&budgId=${record.budgId}`
              )
            }
          >
            查看
          </a>
        ),
      },
    ];
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        <Card className={styles.tableCard}>
          <Alert
            style={{ marginBottom: 16 }}
            message={
              <span>
                作为接单方，实收数据来源于已收费的收费账单，实支数据来源于已回盘的数据，一个签约方一个账单年月一条数据。
              </span>
            }
            type="info"
            showIcon
          />
          <StandardTable
            selectedRows={selectedRows}
            selectedRowKeys={selectedRowKeys}
            rowSelection={null}
            loading={loading}
            data={pageData}
            rowKey="budgId"
            columns={columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default TableList;
